//
//  TCUtils.m
//  E-Book
//

#import "TCUtils.h"
#import "MBProgressHUD.h"
#import "NSString+JsonMethods.h"
#import "ZipArchive.h"
#import "TMDiskCache.h"

@implementation TCUtils

//获取缓存
+ (id)cacheForKey:(NSString *)anAttribute
{
    return [[TMDiskCache sharedCache] objectForKey:anAttribute];
}

//获取AppDelegate
+ (AppDelegate *)App
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
//显示加载视图－自定义
+(void)showLoadingWithView:(UIView *)aView
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:aView];
    HUD.color = [UIColor clearColor];
    HUD.mode = MBProgressHUDModeCustomView;
    [aView addSubview:HUD];
    [HUD show:YES];
    
}

//显示加载视图
+(void)showLoadingWithView:(UIView *)aView text:(NSString *)text customMode:(BOOL)custom
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:aView];
    [aView addSubview:HUD];
    if (!custom) {
        if (text) {
//            HUD.mode = MBProgressHUDModeText;
            HUD.labelText = text;
        }
    }
    else {
        HUD.color = [UIColor clearColor];
        HUD.mode = MBProgressHUDModeCustomView;
    }
    [HUD show:YES];
}

//移除加载视图
+(void)hiddonLoadingWithView:(UIView *)aView
{
    [MBProgressHUD hideAllHUDsForView:aView animated:YES];
}
//封装弹出框的方法
+ (void) showAlertViewWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancel:(NSString *) cancelBtn other: (NSString *) otherBtn tag: (int) tag
{
    if (message == nil)
    {
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:delegate
                                          cancelButtonTitle:cancelBtn
                                          otherButtonTitles:otherBtn, nil];
    alert.tag = tag;
    [alert show];
}
//解析接口返回数据。data接口返回数据。该方法返回字典类型对象
+ (NSDictionary *)getDictionaryWithUTF8Data:(NSData *)data
{
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return [TCUtils dictionaryFromJson:str];
}
//解析接口返回数据。str接口返回数据。该方法返回字典类型对象
+(NSDictionary *) dictionaryFromJson:(NSString *)str{
    NSError *errorJson;
    NSDictionary *ret = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&errorJson];
    return ret;
}
//解压zip压缩包。zipPath压缩包路径；_unzipto解压文件存放路径
+ (BOOL)OpenZip:(NSString*)zipPath unzipto:(NSString*)_unzipto
{
    ZipArchive* zip = [[ZipArchive alloc] init];
    //解压成功
    if( [zip UnzipOpenFile:zipPath] ) {
        BOOL ret = [zip UnzipFileTo:_unzipto overWrite:YES];
        //解压出现错误
        if( NO==ret ) {
            NSLog(@"unzip_error");
        }
        [zip UnzipCloseFile];
        return ret;
    }
    //解压异常
    else {
        NSLog(@"unzip_failed");
        return NO;
    }
}

@end
